<template>
  <div class="auto-fill-container" style="width: 1200px; margin: 20px auto;">
    <div class="results-header">
      <h3 style="text-align: center; width: 100%; margin: 0 0 15px 0">
        村级工程项目详情
      </h3>
    </div>
    <el-form
        :label-width="115"
        label-position="right"
    >
      <!-- 项目名称和项目地址 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="项目名称:">
            <el-input v-model="rowData.projectName" size="small"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目地址:">
            <el-input
                v-model="rowData.constructionAddress"
                size="small"
                autocomplete="on"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 建设内容 -->
      <el-form-item label="主要建设内容:">
        <el-input
            v-model="rowData.constructionContent"
            size="small"
            autocomplete="off"
            type="textarea"
            :rows="4"
            style="width: 100%;"
        />
      </el-form-item>

      <!-- 项目所属地区 -->
      <el-form-item label="项目所属地区:">
        <el-input size="small" disabled/>
      </el-form-item>

      <!-- 资金来源 -->
      <el-form-item label="资金来源:">
        <el-input size="small" disabled/>
      </el-form-item>

      <!-- 建设周期和计划投资总金额 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="建设周期:">
            <el-input v-model="rowData.constructionPeriod" size="small" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划投资总金额:">
            <el-input
                v-model="rowData.totalPrice"
                size="small"
                autocomplete="off"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 决策形式 -->
      <el-form-item label="决策形式:">
        <el-input size="small" disabled/>
      </el-form-item>

      <!-- 决策结果 -->
      <el-form-item label="决策结果:">
        <el-input
            size="small"
            disabled
        />
      </el-form-item>

      <!-- 招标形式和招标单位 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="招标形式:">
            <el-select
                v-model="rowData.biddingForm"
                size="small"
                autocomplete="off"
                class="form-control"
                clearable
            >
              <el-option label="公开招标" value="公开招标"></el-option>
              <el-option label="简易招标" value="简易招标"></el-option>
              <el-option label="简易邀标" value="简易邀标"></el-option>
              <el-option label="直接发包" value="直接发包"></el-option>
              <el-option label="自建" value="自建"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="招标单位:">
            <el-input
                v-model="rowData.biddingUnit"
                size="small"
                autocomplete="on"
                name="biddingUnit"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 项目中标单位和项目中标金额 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="项目中标单位:">
            <el-input
                v-model="rowData.winningBidder"
                size="small"
                autocomplete="on"
                name="winningBidder"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目中标金额:">
            <el-input
                v-model="rowData.bidAmount"
                size="small"
                autocomplete="off"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 项目实施合同 -->
      <el-form-item label="项目实施合同:">
        <el-input size="small" disabled/>
      </el-form-item>

      <!-- 项目承建单位和承建单位负责人 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="项目承建单位:">
            <el-input
                v-model="rowData.constructionUnit"
                size="small"
                autocomplete="on"
                name="constructionUnit"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="承建单位负责人:">
            <el-input
                v-model="rowData.constructionUnitLeader"
                size="small"
                autocomplete="on"
                name="constructionUnitLeader"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 项目启动日期和竣工验收日期 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="项目启动日期:">
            <el-date-picker
                v-model="rowData.projectStartDate"
                type="date"
                size="small"
                autocomplete="off"
                placeholder="选择启动日期"
                style="width: 100%;"
                :disabled-date="(time) => time.getTime() > Date.now() || time.getTime() < new Date('2018-12-31').getTime()"
                disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="竣工验收日期:">
            <el-date-picker
                v-model="rowData.completionDate "
                type="date"
                size="small"
                autocomplete="off"
                placeholder="选择验收日期"
                style="width: 100%;"
                :disabled-date="(time) => time.getTime() > Date.now() || time.getTime() < new Date('2018-12-31').getTime()"
                disabled
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 项目监督人员和竣工验收人员 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="项目监督人员:">
            <el-input
                v-model="rowData.constructionSupervisor"
                size="small"
                autocomplete="on"
                name="constructionSupervisor"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="竣工验收人员:">
            <el-input
                v-model="rowData.constructionEndPerson"
                size="small"
                autocomplete="on"
                name="constructionEndPerson"
            />
          </el-form-item>
        </el-col>
      </el-row>


      <el-form-item label="竣工验收意见:">
        <el-input
            v-model="rowData.constructionEndOpinion"
            size="small"
            autocomplete="on"
            clearable
        />
      </el-form-item>

    </el-form>

    <!-- 第14行：1列 - 提交按钮 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <div style="display: flex; justify-content: flex-end; gap: 10px;">
          <el-button
              size="small"
              @click="handleBack"
              style="margin: 0; width: 60px;"
          >
            返回
          </el-button>
          <el-button
              size="small"
              title="数据提交到服务器保存，小微权力平台可以直接读取，数据在10分钟内有效"
              type="primary"
              @click="handleProcessAndTransfer"
              :disabled="!rowData"
              style="margin: 0; width: 60px;"
          >
            提交
          </el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {ref, onMounted, nextTick, watch, shallowRef} from 'vue';
import {useRouter} from 'vue-router';
import axios from 'axios'
import {formatDate} from "@/utils/commonUtils";
import {ElMessage} from 'element-plus'

// 定义数据源
const baseUrl = process.env.VUE_APP_API_BASE_URL;

const props = defineProps({
  rowData: {
    type: Object,
    required: true
  }
})

const rowData = ref(props.rowData)
const router = useRouter();

const emit = defineEmits(['close'])

// 存储设备指纹的响应式变量
const deviceFingerprint = shallowRef('')

// 建设周期计算核心逻辑
const calculateConstructionPeriod = () => {
  const {projectStartDate, completionDate} = rowData.value;

  if (!projectStartDate) {
    rowData.value.constructionPeriod = '';
    return;
  }

  // 格式化启动日期
  const formattedStart = formatDate(projectStartDate, 10);

  if (completionDate) {
    // 格式化验收日期
    const formattedEnd = formatDate(completionDate, 10);
    rowData.value.constructionPeriod = `${formattedStart} - ${formattedEnd}`;

    // 如果输入了竣工验收日期且竣工验收意见为空，则设置为"验收合格"
    if (!rowData.value.constructionEndOpinion) {
      rowData.value.constructionEndOpinion = '验收合格';
    }
  } else {
    // 格式化当前年最后一天
    const currentYear = new Date().getFullYear();
    const endOfYear = `${currentYear}-12-31`;
    const formattedEnd = formatDate(endOfYear, 10);
    rowData.value.constructionPeriod = `${formattedStart} - ${formattedEnd}`;
  }
};

// 监听日期变化自动触发计算
watch(
    [() => rowData.value.projectStartDate, () => rowData.value.completionDate],
    () => calculateConstructionPeriod(),
    {immediate: true}
);

// 提取设备指纹生成逻辑到独立函数
const initializeDeviceFingerprint = async () => {
  // 收集更丰富的设备特征
  const features = {
    userAgent: navigator.userAgent,
    screenResolution: `${window.screen.width}x${window.screen.height}`,
    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    hardwareConcurrency: navigator.hardwareConcurrency || 'unknown',
    language: navigator.language,
    platform: navigator.platform,
    vendor: navigator.vendor,
    doNotTrack: navigator.doNotTrack,
    cookieEnabled: navigator.cookieEnabled,
    plugins: navigator.plugins.length,
    mimeTypes: navigator.mimeTypes.length,
    canvas: await getCanvasFingerprint(),
    WebGL: await getWebGLFingerprint(),
    audio: await getAudioFingerprint(),
    localStorage: localStorage.getItem('fingerprint') || '',
    sessionStorage: sessionStorage.getItem('fingerprint') || '',
  };

  // 序列化特征数据
  const dataString = JSON.stringify(features);

  // 使用哈希算法
  const cyrb53 = function (str, seed = 0) {
    let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
    for (let i = 0, ch; i < str.length; i++) {
      ch = str.charCodeAt(i);
      h1 = Math.imul(h1 ^ ch, 2654435761);
      h2 = Math.imul(h2 ^ ch, 1597334677);
    }
    h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
    h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
    return (h2 >>> 0).toString(16).padStart(8, '0') + (h1 >>> 0).toString(16).padStart(8, '0');
  };

  return cyrb53(dataString);
};

// 获取 Canvas 指纹
async function getCanvasFingerprint() {
  try {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    ctx.font = '14px sans-serif';
    ctx.textAlign = 'center';
    ctx.fillText('Hello World', 100, 100);
    return canvas.toDataURL();
  } catch (e) {
    return 'canvas-error';
  }
}

// 获取 WebGL 指纹
async function getWebGLFingerprint() {
  try {
    const canvas = document.createElement('canvas');
    const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
    if (!gl) return 'webgl-not-supported';

    const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
    const vendor = debugInfo ? gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) : 'unknown';
    const renderer = debugInfo ? gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) : 'unknown';

    return `${vendor}-${renderer}`;
  } catch (e) {
    return 'webgl-error';
  }
}

// 获取 Audio 指纹
async function getAudioFingerprint() {
  try {
    const audioContext = new (window.AudioContext || window.webkitAudioContext)();
    const buffer = audioContext.createBuffer(1, 1, 44100);
    const source = audioContext.createBufferSource();
    source.buffer = buffer;
    source.connect(audioContext.destination);
    source.start();

    const data = await new Promise((resolve) => {
      const dataArray = new Float32Array(buffer.length);
      const analyzer = audioContext.createAnalyser();
      analyzer.fftSize = 256;
      analyzer.connect(audioContext.destination);
      analyzer.getByteFrequencyData(dataArray);
      resolve(dataArray.join(','));
    });

    return data;
  } catch (e) {
    return 'audio-error';
  }
}

// 处理传入数据
onMounted(async () => {
  await nextTick();

  deviceFingerprint.value = await initializeDeviceFingerprint();

  if (props.rowData) {
    rowData.value = props.rowData;

    // 保留原有的数据处理逻辑
    if (!rowData.value.biddingForm) {
      rowData.value.biddingForm = '简易招标';
    }

    const winningBidderName = rowData.value.winningBidder?.trim() || '';
    const isIndividual = winningBidderName.length < 5;

    rowData.value.constructionUnit = winningBidderName;
    rowData.value.constructionUnitLeader = isIndividual ? winningBidderName : '';

    if (rowData.value.townName) {
      document.title = `村级工程项目详情 - ${rowData.value.townName}`;
    }
  }
});

// 数据组织与标准化
const organizeRawData = () => {
  const raw = rowData.value || {};
  const biddingForm = raw.biddingForm?.trim() || '简易发包';
  const winningBidderName = (raw.winningBidder || '').trim();
  const isIndividual = winningBidderName.length < 5;
  return {
    townName: raw.townName || '',
    projectName: raw.projectName?.trim() || '',
    constructionContent: raw.constructionContent?.trim() || '',
    constructionAddress: raw.constructionAddress?.trim() || '',
    biddingForm: biddingForm,
    biddingUnit: raw.biddingUnit?.trim() || '',
    winningBidder: winningBidderName,
    bidAmount: raw.bidAmount ? Number(raw.bidAmount).toFixed(2) : '',
    constructionUnit: winningBidderName || '',
    constructionUnitLeader: raw.constructionUnitLeader?.trim() || (isIndividual ? winningBidderName : ''),
    constructionSupervisor: raw.constructionSupervisor?.trim() || '',
    constructionEndPerson: raw.constructionEndPerson?.trim() || '',
    constructionEndOpinion: raw.constructionEndOpinion?.trim() || '',
    totalPrice: raw.totalPrice ? Number(raw.totalPrice).toFixed(2) : '',
    winningTime: raw.winningTime || '',
    constructionPeriod: raw.constructionPeriod || '',
    projectStartDate: formatDate(raw.projectStartDate, 10),
    completionDate: formatDate(raw.completionDate, 10),
  };
};

// 数据处理与传输
const handleProcessAndTransfer = async () => {
  // 验收日期与启动日期比较校验
  const {projectStartDate, completionDate} = rowData.value;
  if (projectStartDate && completionDate) {
    const start = new Date(projectStartDate);
    const end = new Date(completionDate);
    if (end < start) {
      ElMessage.error('验收日期不能早于启动日期，请修正后再提交');
      return;
    }
  }

  try {
    const data = {
      ...organizeRawData(),
      fingerprint: deviceFingerprint.value,
    };

    const response = await axios.post(`${baseUrl}/searchapi/searchdata/upload`, data);
    if (response.data.success) {
      ElMessage.success('提交成功');

      // 通过 BroadcastChannel 发送数据到其他页面
      try {
        const channel = new BroadcastChannel('project-data-channel');
        channel.postMessage({
          type: 'PROJECT_DATA_TRANSFER',
          data: data,
          timestamp: Date.now()
        });

        // 延迟关闭，确保消息发送完成
        setTimeout(() => {
          channel.close();
        }, 1000);
      } catch (error) {
        console.error('BroadcastChannel 发送失败:', error);
      }

      emit('close');
    } else {
      ElMessage.error(response.data.message || '提交失败');
    }
  } catch (error) {
    console.error('处理传输失败:', error);
    ElMessage.error('提交失败，请重试');
    throw error;
  }
};

const handleBack = () => {
  emit('close')
}
</script>


<style scoped lang="scss">
.auto-fill-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  font-size: 14px;
}

.grid-content {
  height: 36px;
  border-radius: 4px;
  background-color: #f0f2f5;
  display: flex;
  align-items: center;
  padding: 0;
  font-size: 14px; /* 统一设置内容区域文字大小 */
}

/* 字段容器样式 */
.el-form-item__label {
  width: 112px !important; /* 强制标签宽度 */
  font-size: 14px;
}

/* 调整表单项间距 */
.el-form-item {
  margin-bottom: 15px;
}

/* 结果展示样式 */
.results-header {
  border-bottom: 2px solid #e6e6e6;
  margin-bottom: 20px;
}

/* 统一输入框高度为32px */
.el-input__inner {
  height: 32px !important;
  line-height: 32px !important;
  font-size: 14px !important;
}

.el-input {
  height: 32px !important;
}

.el-button--small {
  height: 32px !important;
  line-height: 32px !important;
}

/* 为建设内容多行文本框容器添加样式 */
.content-textarea-container {
  height: auto !important; /* 覆盖固定高度限制 */
  padding: 10px; /* 增加内边距 */
  min-height: 100px; /* 设置最小高度 */
}

/* 调整多行文本框样式 */
.el-textarea__inner {
  font-size: 14px !important;
  resize: vertical; /* 允许垂直调整大小 */
}

.el-button {
  font-size: 14px !important;
}

::v-deep(.el-select .el-select__wrapper) {
  height: 32px !important;
  line-height: 32px !important;
  min-height: 32px !important;
  border: 1px solid #dcdfe6 !important;
  border-radius: 4px !important;
  box-shadow: none !important;
}

::v-deep(.el-date-editor.el-input, .el-select .el-select__wrapper) {
  height: 32px !important;
  line-height: 32px !important;
  min-height: 32px !important;
  border-radius: 4px !important;
  box-shadow: none !important;
}

/* 统一设置禁用输入框背景色 */
:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #f3f5f8 !important;
}
</style>